// stores/category.ts
import { defineStore } from 'pinia'
import { deleteCategory, getCategories, updateCategory, createCategory } from '@/api/modules/product'
import useMessage from '@/plugin/useMessage'

export const useCategoryStore = defineStore('category', {
  state: () => ({
    categories: [] as CategoryItem[],
    loading: false,
    editorIndex: -1,
    createMode: false
  }),
  actions: {
    async fetchCategories() {
      this.loading = true
      const res = await getCategories()
      if (res.code === 200) {
        this.categories = res.data
      }
      this.loading = false
    },
    //更新
    async updateItem(id: number, payload: { name: string }) {
      const res = await updateCategory(id, payload)
      if (res.code === 200) {
        const index = this.categories.findIndex(item => item.id === id)
        if (index > -1) this.categories[index].name = payload.name
      }
      useMessage(res.code, res.message)
    },
    //删除
    async deleteItem(id: number) {
      const res = await deleteCategory(id)
      if (res.code === 200) {
        this.categories = this.categories.filter(item => item.id !== id)
      }
      useMessage(res.code, res.message)
    },
    //新增
    async createItem(payload: { name: string }) {
      const res = await createCategory(payload)
      if (res.code === 200) {
        await this.fetchCategories()
        this.createMode = false
      }
      useMessage(res.code, res.message)
    }
  },
  persist: true // 启用持久化存储（需安装插件）
})
export default useCategoryStore